package com.caih.student.controller;

import com.caih.student.entity.Student;
import com.caih.student.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/*
@author zhouxiaojia
@create 2019-07-16 下午 03:41
*/
    @RestController
    //注入StudentService的bean
    public class StudentController {

    @Autowired
    private StudentService service;



    /**
     * 根据id删除学生
     *
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id) {
        try {
            service.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "删除成功！";
    }

    /**
     * 根据id更新学生
     *
     * @param student
     * @return
     */
    @PutMapping("/update")
    public Student update(Student student) {
        Student update = service.update(student);
        return update;
    }

    /**
     * 查询所有学生
     *
     * @return
     */
    @GetMapping("/queryAll")
    public List<Student> queryAll() {
        List<Student> students = service.queryAll();
        return students;
    }

    /**
     * 根据id查询学生
     *
     * @param id
     * @return
     */
    @GetMapping("/query/{id}")
    public Student queryById(@PathVariable Integer id) {
        Student student = service.queryById(id);
        return student;
    }

    /**
     * 根据stuNo查询学生
     * @param stuNo
     * @return
     */
    @GetMapping("/query2/{stuNo}")
    public Object queryByStuNo(@PathVariable String stuNo){
        int flag = service.searchStuNo(stuNo);
        if(flag == 0) return "记录不存在";
        else{
                Student student = service.queryByStuNo(stuNo);
                return student;
            }
        }

    /*
    *根据学号插入学生信息，并检测是否已存在

    * @param stuNo
    * @return
     */
    @PostMapping("/save")
    public Object save (Student student){
        int flag = service.searchStuNo(student.getStuNo());
        if(flag == 1) return "记录已存在";
        else{
            Student save = service.save(student);
            return save;
        }
    }

}